package top.wshape1.shiziapi.common.utils;

import com.alibaba.fastjson2.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import top.wshape1.shiziapi.common.domain.CommonUser;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

public class JwtUtil {

//    public static void main(String[] args) {
//        CommonUser commonUser = new CommonUser();
//        commonUser.setId(2L);
//        commonUser.setEmail("wuxing233@qq.com");
//        commonUser.setNickname("wuxing233");
//        commonUser.setAvatarUrl("https://shiziapi.oss-cn-shenzhen.aliyuncs.com/user_avatars/2.png");
//        commonUser.setStatus(1);
//        System.out.println(createJWT("2", JSON.toJSONString(commonUser), "Wshape1Wshape1Wshape1Wshape1Wshape1", 1L));
//    }

    // 有效期 1d
    public static final Long JWT_TTL = 86400000L;

    // JWT令牌信息 必须大于等于32个字符
//    public static final String JWT_KEY = "Wshape1Wshape1Wshape1Wshape1Wshape1";

    public static String createJWT(String id, String subject, String signKey) {
        return createJWT(id, subject, signKey, null);
    }


    public static String createJWT(String id, String subject, String signKey, Long ttlMillis) {

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        if (ttlMillis == null) {
            ttlMillis = JWT_TTL;
        }

        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);

        SecretKey secretKey = generalKey(signKey);

        JwtBuilder builder = Jwts.builder()
                .setId(id)                      // 设置唯一编号
                .setSubject(subject)            // 设置主题 可以是JSON数据
                .setIssuer("Wshape1")
                .setIssuedAt(now)               // 设置签发日期
                .setExpiration(expDate)         // 设置过期时间
                // 设置签名 使用HS256算法 并设置SecretKey(字符串)
                .signWith(secretKey, SignatureAlgorithm.HS256);
        return builder.compact();


    }

    /**
     * 生成加密secretKey
     *
     * @return
     */
    public static SecretKey generalKey(String signKey) {
        byte[] encodedKey = Base64.getEncoder().encode(signKey.getBytes());
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, SignatureAlgorithm.HS256.getJcaName());
    }

    /**
     * 解析令牌数据
     */
    public static Claims parseJWT(String jwt, String signKey) {
        SecretKey secretKey = generalKey(signKey);
        return Jwts.parserBuilder()
                .setSigningKey(secretKey)
                .build()
                .parseClaimsJws(jwt)
                .getBody();
    }
}

